package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * ClassName:StringToBaseEnumConverterFactory
 * Package: com.atguigu.lease.web.admin.custom.converter
 * Description:
 *
 * @Author Makabaka
 * @Create 2024/9/20 18:38
 * @Version 1.0
 */

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
//    T泛型的上限是BaseEnum  参数中的targetType与mvc提供的转换器中的参数一样 代表枚举类的内容
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
//                遍历枚举中的每一个属性，判断与传来的source是否相同
                for (T constant : targetType.getEnumConstants()) {
                    if (constant.getCode().equals(Integer.valueOf(source))){
                        return constant;
                    }
                }
//                用lambda表达式写
//                return source -> {
//                遍历枚举中的每一个属性，判断与传来的source是否相同
//                    for (T constant : targetType.getEnumConstants()) {
//                        if (constant.getCode().equals(Integer.valueOf(source))){
//                            return constant;
//                        }
//                    }
                throw new RuntimeException("参数错误");
            }
        };
    }
}
